const query = require('../db');
const util = require('../util');
module.exports={
    //用户注册
    registerUser(data,callback){
        let sql = `INSERT INTO \`user\` (userName,userPsd,problemId,problemAnswer)  VALUES ('${data.userName}','${data.userPsd}','${data.problemId}','${data.problemAnswer}')`;
        query(sql,(err,data)=>{
             if(err){
                 callback({status:0,err});
             }else {
                 callback({status:1,data:'注册成功'});
             }
        })
    },
    //用户登录
    loginUser(data,callback){
        let sql = `SELECT id FROM \`user\` WHERE userName='${data.userName}' AND userPsd='${data.userPsd}' `;
        query(sql,(err,data)=>{
            if(err){
                callback({status:0,err});
            }else {
                callback({status:1,data});
            }
        })
    },
    //根据用户ID获取用户信息
    userInfoById(id,callback){
        let sql = `SELECT * FROM \`user\` WHERE id=${id} `;
        query(sql,(err,data)=>{
            if(err){
                callback({status:0,err});
            }else {
                callback({status:1,data});
            }
        })
    },
    //根据密保问题ID和答案修改密码
    modifyPSD(data,callback){
        let sql=`UPDATE \`user\` SET userPsd='${data.userPsd}' WHERE problemID='${data.problemID}' AND problemAnswer='${data.problemAnswer}' AND userName='${data.userName}'`;
        query(sql,(err,data)=>{
            if(err){
                callback({status:0,err});
            }else {
                if(data.changedRows==1){
                    callback({status:1,msg:'重置密码成功'});
                }else {
                    callback({status:0,err:'重置密码失败'});
                }
            }
        })
    },
    //根据用户ID创建答题卡
    createAnswer(userID,data,callback){
        let date = new Date();
        let time = date.getFullYear()+'-'+(date.getMonth())+'-'+date.getDate()+' '+date.getHours()+':00:00';
        let sql;
        if(userID){
            sql =`INSERT INTO answerCard(userID,content,createTime) VALUES(${userID},'${data.content}','${time}')`;
        }else {
            sql=`INSERT INTO answerCard(content,createTime) VALUES('${data.content}','${time}')`;
        }
        query(sql,(err,data)=>{
            if(err){
                console.log(err);
                callback({status:0,err});
            }else {
                callback({status:1,msg:'提交成功'});
            }
        })
    },
    //根据用户ID获取答题卡
    getAnswerList(userID,callback){
        let sql = `SELECT * FROM answerCard WHERE userID=${userID}  ORDER BY createTime DESC`;
        query(sql,(err,data)=>{
            if(err){
                console.log(err);
                callback({status:0,err});
            }else {
                callback({status:1,data});
            }
        })
    }
};
